/*  
 *  Copyright 2006 Paul Jack.
 *
 *  This file is part of the Dex compiler suite. 
 *  
 *  Dex is free software; you can redistribute it and/or modify it
 *  under the terms of the GNU General Public License as published by the
 *  Free Software Foundation; either version 2 of the License, or (at your
 *  option) any later version.
 *  
 *  Dex is distributed in the hope that it will be useful, but
 *  WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
 *  Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
 */
package dex.compiler.interpreter;


import java.util.ArrayList;

import dex.compiler.interpreter.value.Value;
import dex.compiler.model.base.Identifiers;
import dex.compiler.model.definition.Function;
import dex.compiler.model.definition.Unit;
import dex.compiler.model.program.Path;
import dex.compiler.model.program.Program;


/**
 * An interpreter for Dex programs.
 */
public class Interpreter {

	
	/**
	 * The interpeter's state.
	 */
	private State state;


	/**
	 * Used to kick off interpretations.
	 */
	private StatementExecutor walker;


	/**
	 * Constructs a new <code>Interpreter</code>.
	 * 
	 * @param  program   the program to interpret
	 */
	public Interpreter(Program program) {
		State state = new State(program);
		this.state = state;
		this.walker = new ExpressionEvaluator(state);
	}


	/**
	 * Executes a function, returning the result.
	 * 
	 * @param qualifiedName  the fully-qualified name of the toplevel function to execute
	 * @return  the return value of that function, or <code>null</code> if the function
	 *   is void
	 */
	public Object execute(String qualifiedName) {
		String unitName = Identifiers.getUnit(qualifiedName);
		String functionName = Identifiers.getBase(qualifiedName);
		Unit unit = state.getProgram().loadComplete(unitName);
		for (Function f: unit.getFunctions()) {
			if (f.getName().equals(functionName) && f.getParameters().isEmpty()) {
				Path path = new Path(state.getProgram(), unit, unit, f);
				return walker.execute(path, new ArrayList<Value>(), null);
			}
		}
		throw new IllegalStateException("No such function: " + qualifiedName + "()");
	}

}
